<script setup>
import Map from '@src/Map/map';
import Request from '../request';
import { myToken } from '@src/config/sysConfig';
import { onMounted, ref } from 'vue';
//巡航者
import Car from './car/index.js';
import Plane from './plane/index.js';
// 巡航类
import Cruise from '@src/Map/gisMethod/Cruise';

let viewer;

onMounted(() => {
  Request.getJson('./config/mapCfg.json', (r) => {
    viewer = new Map('mapContainer', initPosition, true, r, myToken, 0);
    viewer.switchLayer('supermap-dark');

    viewer.addEvent('aa', 'LEFT_CLICK', (e) => {
      console.log(e);
    });

    viewer.setView([116.3677, 39.9041, 3566, 10, -28, 0], 0);
    addBuilding();
    addCar();
    addPlane();
    addCruise();
  });
});

// 添加巡航者
const addCar = () => {
  new Car(viewer);
  viewer.clock.shouldAnimate = true;
};

// 添加无人机
const addPlane = () => {
  new Plane(viewer);
  viewer.clock.shouldAnimate = true;
};

//巡航
const addCruise = () => {
  //   czml方式添加无人机巡航
  const pointArr = [
    [116.36578323959371, 39.94717447037612, 100],
    [116.40200620078545, 39.94788986593708, 100],
    [116.40300620078545, 39.96788986593708, 100],
    [116.40126332543285, 39.9870228957151, 100],
    [116.36315522148672, 39.985919757736404, 100],
    [116.36578323959371, 39.94717447037612, 100],
  ];
  cruise = new Cruise(viewer);
  cruise.loadDataInfo({ pointArr, speed: 10 });
  if (cruise.isLoadData) {
    cruise.add({ isFollow: true });
  }
};

//楼宇
function addBuilding(isShader = true) {
  const tileIp =
    'http://61.50.111.214:18191/3clear/imee/IMEE-Globe-Projects/3Dtileset/beijing/tileset.json';
  const building = viewer.load3DTiles('3dtiles', {
    url: tileIp,
  });
  if (isShader) {
    changeCesiumShader();
  } else {
    //   viewer.extend(Cesium.viewerCesium3DTilesInspectorMixin);
    const heightStyle = new Cesium.Cesium3DTileStyle({
      color: {
        conditions: [
          ['${floor} >= 300', 'rgba(45, 0, 75, 0.5)'],
          ['${floor} >= 200', 'rgb(102, 71, 151)'],
          ['${floor} >= 100', 'rgb(170, 162, 204)'],
          ['${floor} >= 50', 'rgb(224, 226, 238)'],
          ['${floor} >= 25', 'rgb(252, 230, 200)'],
          ['${floor} >= 10', 'rgb(248, 176, 87)'],
          ['${floor} >= 5', 'rgb(198, 106, 11)'],
          ['true', 'rgb(127, 59, 8)'],
        ],
      },
    });

    building.style = heightStyle;
  }
}

function changeCesiumShader() {
  Cesium.ForEach.shader = function (gltf, handler) {
    if (Cesium.hasExtension(gltf, 'KHR_techniques_webgl')) {
      // -----用IsBlink和"cesiumlab"标识智慧城市---------------------------------------
      //   console.log(gltf.asset.generator);
      if (true && gltf.asset.generator === 'cesiumlab') {
        const SRC = {
          FS: `
                  #ifdef GL_ES
                  precision highp float;
                  #endif
                  
                  uniform mat4 u_modelViewMatrix;
                  uniform mat4 u_projectionMatrix;
                  uniform mat3 u_normalMatrix;
                  attribute vec3 a_position;
                  attribute vec3 a_normal;
                  attribute float a_batchId;   

                  varying vec3 v_positionEC;
                  varying vec3 v_normal;
                  varying vec3 v_position;

                  void main(void) {
                      vec4 position = vec4(a_position, 1.0);
                      gl_Position = u_projectionMatrix * u_modelViewMatrix * position;
                      v_normal = u_normalMatrix * a_normal;
                      v_position = v_positionEC = position.xyz;
                  }\
                  `,
        };
        gltf.extensions.KHR_techniques_webgl.shaders[0].extras._pipeline.source =
          SRC.FS;

        let number1 =
          gltf.extensions.KHR_techniques_webgl.shaders[1].extras._pipeline.source.indexOf(
            ';'
          ) + 1;
        let sky1 =
          gltf.extensions.KHR_techniques_webgl.shaders[1].extras._pipeline.source.substring(
            0,
            number1
          );
        let sky2 =
          gltf.extensions.KHR_techniques_webgl.shaders[1].extras._pipeline.source.substring(
            number1
          );
        sky1 += 'varying vec3 v_position;';
        gltf.extensions.KHR_techniques_webgl.shaders[1].extras._pipeline.source =
          sky1 + sky2;

        number1 =
          gltf.extensions.KHR_techniques_webgl.shaders[1].extras._pipeline.source.lastIndexOf(
            '}'
          );
        sky1 =
          gltf.extensions.KHR_techniques_webgl.shaders[1].extras._pipeline.source.substring(
            0,
            number1
          );

        sky2 = {
          FS: `
                      gl_FragColor = vec4(0, 0.5, 1.0, 1.0); // // 物体的基础颜色
                      
                      float baseHeit = 0.0;    // 物体的基础高度
                      float heitRange = 60.0;  // 高亮的变化范围
                      float heitGlowRange = 300.0; // 光环的移动范围(高度)
          
                      // 120帧一个周期 改变当前高度的颜色 sin函数
                      float dlHeit = v_position.z - baseHeit;
                      float curPI = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
                      float curRGB = dlHeit / heitRange + sin(curPI) * 0.1; 
                      gl_FragColor *= vec4(curRGB, curRGB, curRGB, 1.0);
          
                      // 动态光环 360帧一个周期
                      float scaleFrame = fract(czm_frameNumber / 360.0); 
                      scaleFrame = abs(scaleFrame - 0.5) * 2.0;
                      float scaleHeit = clamp(dlHeit / heitGlowRange, 0.0, 1.0);
                      // step(edge,x) x<edge时返回0 否则返回1
                      float diff = step(0.005, abs(scaleHeit - scaleFrame));
                      gl_FragColor.rgb += gl_FragColor.rgb * (1.0 - diff);
                      
                  }
                  `,
        };
        gltf.extensions.KHR_techniques_webgl.shaders[1].extras._pipeline.source =
          sky1 + sky2.FS;
        return Cesium.ForEach.object(
          gltf.extensions.KHR_techniques_webgl.shaders,
          handler
        );
      }
      // ------------------------------------------------------------------------------
      return Cesium.ForEach.object(
        gltf.extensions.KHR_techniques_webgl.shaders,
        handler
      );
    }
    return Cesium.ForEach.topLevel(gltf, 'shaders', handler);
  };
}
</script>


<template>
  <div id="tileset">
    <div id="mapContainer" />
  </div>
</template>


<style lang="scss">
#tileset {
  width: 100%;
  height: 100%;
  overflow: hidden;

  #mapContainer {
    width: 100%;
    height: 100%;
    .cesium-widget canvas {
      width: 100%;
      height: 100%;
      position: absolute;
    }
  }

  #Roller {
    #slider {
      position: absolute;
      left: 50%;
      top: 0px;
      background-color: #d3d3d3;
      width: 5px;
      height: 100%;
      z-index: 1;
      cursor: ew-resize;

      #angle {
        font-size: 10px;
        text-align: center;
        z-index: 4;
        transform: translateX(-3px);
        display: none;
        top: calc(50% - 10px);
        left: -15px;
        color: #000;
        height: 40px;
        width: 40px;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        background: url('./assets/angle.png');
        border-radius: 20px;
        position: absolute;
        cursor: pointer;
      }
    }
    .active {
      color: #66defaff;
    }

    .tool {
      padding: 0 10px;
      width: 150px;
      z-index: 2;
      height: 30px;
      position: absolute;
      background: #0e0c0ca8;
      color: #fff;
      border-radius: 10px;
      top: 20px;
      margin: 10px;
      display: grid;
      align-items: center;
      grid-template-columns: 1fr 1fr 1fr;
      justify-items: center;
      right: 20px;
      font-size: 15px;
      section {
        cursor: pointer;
      }
    }
    .tool2 {
      @extend .tool;
      width: 180px;
      grid-template-columns: 1fr 1fr 1fr 1fr;
    }
    #control {
      position: fixed;
      width: 120px;
      z-index: 5;
      right: 51px;
      top: 80px;
      cursor: pointer;
      display: flex;
      height: 120px;
      justify-items: center;
      align-items: center;
      grid-row-gap: 1px;
      background-image: url('./assets/back.png');
      background-size: 100% 100%;
      img {
        max-width: 120%;
      }
      .center {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-column-gap: 5px;
        justify-items: center;
        align-items: center;
        #angleImg {
          height: 40px;
          width: 40px;
          background-repeat: no-repeat;
          background-size: 100% 100%;
          background: url('./assets/angle.png');
        }
      }
    }
  }
}
</style>